package com.larsgard.gedviewer.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Date;
import java.util.UUID;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.larsgard.gedviewer.server.storage.GedFile;
import com.larsgard.gedviewer.server.storage.GedFileStorage;
import com.larsgard.gedviewer.server.storage.TreeStorage;
import com.larsgard.gedviewer.server.storage.entities.JDOUserTree;

public class UploadServlet extends HttpServlet {

    private static final String NOT_LOGGED_IN = "NOT_LOGGED_IN";
    private static final String OK = "OK";
    private static final long serialVersionUID = 934428178218856058L;
    private static final String FAIL = "FAIL";

    private static final TreeStorage treeStorage = TreeStorage.getInstance();

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

	UserService userService = UserServiceFactory.getUserService();
	User user = userService.getCurrentUser();
	PrintWriter writer = response.getWriter();
	response.setContentType("text/html");
	if (user == null) {
	    writer.write(NOT_LOGGED_IN);
	    return;
	}

	String status = storeFileReturnStatus(request, user);
	writer.write(status);
    }

    private String storeFileReturnStatus(HttpServletRequest request, User user) throws IOException {
	if (ServletFileUpload.isMultipartContent(request)) {

	    ServletInputStream inputStream = request.getInputStream();
	    // while ((available = inputStream.available()) > 0) {
	    // int read = inputStream.read(file, offset, available);
	    // offset += read;
	    // }

	    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
	    // discard 3 lines;
	    for (int i = 0; i < 3; i++) {
		reader.readLine();
	    }
	    String lastLine = reader.readLine();
	    StringBuffer content = new StringBuffer();
	    String line = null;
	    while ((line = reader.readLine()) != null) {
		content.append(lastLine + "\r\n");
		lastLine = line;
	    }
	    String treeId = UUID.randomUUID().toString();

	    GedFile gedFile = new GedFile();
	    gedFile.setGedFile(new Text(content.toString()));
	    gedFile.setFileId(UUID.randomUUID().toString());
	    gedFile.setTreeId(treeId);
	    GedFile storedFile = GedFileStorage.getInstance().storeFile(gedFile);

	    JDOUserTree tree = new JDOUserTree();
	    tree.setCreatedDate(new Date(System.currentTimeMillis()));
	    tree.setPassword(UUID.randomUUID().toString());
	    tree.setUserMail(user.getEmail());
	    tree.setGedFileId(storedFile.getFileId());
	    tree.setTreeId(treeId);

	    JDOUserTree storeTree = treeStorage.storeTree(tree);
	    if (storeTree != null) {
		return OK;
	    }
	}
	return FAIL;
    }
}
